package dto

import (
	"context"
	"engine/cache"
	"engine/consts"
	"engine/model"
	"errors"
	"fmt"
	"gorm.io/gorm"
	"lib/db"
	"lib/log"
	sferrors "lib/sf-errors"
	"strconv"
	"strings"
	"time"
)

func GetCachedActiveSysUserById(ctx context.Context, uId uint64) (*model.SysUserDetail, error) {
	cacheKey := cache.GetUserCacheName(uId, consts.ModuleAdmin)
	user, err := cache.RedisContextGet[*model.SysUserDetail](ctx, cacheKey)
	if err == nil {
		return *user, nil
	}

	userNew, err := GetSysUserDetailById(uId)
	if err != nil {
		return nil, err
	}
	if userNew == nil {
		return nil, nil
	}

	err = cache.RedisContextSet(ctx, cacheKey, userNew, consts.DataCacheTime)
	if err != nil {
		log.Errorf("uid %d,保存redis失败：%v ", uId, err)
		return nil, err
	}
	return userNew, nil
}

func GetActiveSysUserDetailMobile(mobile string) (*model.My_user, error) {
	var user model.My_user
	query := db.GetDb()
	query = query.Where("status = ?", consts.StatusNormal)
	err := query.Where("mobile = ?", mobile).First(&user).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, nil
		}
		return nil, err
	}
	return &user, nil
}

func QuerySysUserList(query string, status consts.CommonStatus, page int, pageSize int) (*PaginationList[model.SysUserDetail], error) {
	q := db.GetDb()
	if query != "" {
		q = q.Where(
			q.Where("nickname LIKE ?", "%"+query+"%").Or("email LIKE ?", "%"+query+"%"),
		)
	}
	if status != "" {
		q = q.Where("status = ?", status)
	}
	q = q.Preload("Roles", "module = ?", consts.ModuleAdmin)
	return Paginate[model.SysUserDetail](q, &PaginatorOption{
		Page:     page,
		PageSize: pageSize,
	})
}

func QuerySysUserByMobile(email string) (*model.My_user, error) {
	return QueryOne[model.My_user]("mobile = ?", email)
}
func QuerySysUserByQrcode(invitationCode string) (*model.My_user, error) {
	return QueryOne[model.My_user]("q = ?", invitationCode)
}
func CreateSysUser(sysUser *model.My_user) error {
	return db.GetDb().Omit("create_time").Create(sysUser).Error
}
func GetXianzhi() *model.Xianzhi {
	nowTime := time.Now().Format("1504")
	IntNow, err := strconv.Atoi(nowTime)
	if err != nil {
		return nil
	}
	zhuan := 0
	zhuanStr := "通用积分 转赠时间 10:00到18:00"
	if IntNow > 1000 && IntNow < 1800 {
		zhuan = 1
	}

	renZheng := 0
	renStr := "认证时间为 08:00到22:00"
	if IntNow > 800 && IntNow < 2200 {
		renZheng = 1
	}
	return &model.Xianzhi{
		Zheng:    renZheng,
		ZhengStr: renStr,
		Zhuan:    zhuan,
		ZhuanStr: zhuanStr,
	}
}

func HandelUserDetail(sysUser *model.My_user) (*model.SysUserDetailResp, error) {

	//birthday := fmt.Sprintf("%s%s%s", m[5], m[6], m[7]) 对比时间

	xianzhi := GetXianzhi()
	mmm := 0
	if sysUser.OldLevel > 29 {
		var ddd int64
		db.GetDb().Debug().Model(&model.My_user{}).Where("pid= ? and is_task>0", sysUser.Id).Count(&ddd)
		if ddd > 0 {
			mmm = 44
		}
	}

	return &model.SysUserDetailResp{
		Id:         sysUser.Id,
		Nickname:   sysUser.Nickname,
		Mobile:     sysUser.Mobile,
		Money:      sysUser.Money,
		Score:      sysUser.Score,
		Token:      sysUser.Token,
		Q:          sysUser.Q,
		Qrcode:     sysUser.Qrcode,
		DyTure:     sysUser.DyTure,
		DyUsername: sysUser.DyUsername,
		Xianzhi:    *xianzhi,
		Point:      sysUser.Point,
		IsTask:     sysUser.IsTask,
		Jt:         sysUser.Jt,
		N:          sysUser.N,
		EndDate:    sysUser.EndDate,
		T:          sysUser.T,
		CreateTime: sysUser.CreateTime,
		Level:      mmm,
		Jhs:        sysUser.Jhs,
		Gold:       sysUser.Gold,
		Tz:         sysUser.Tz,
		WLevel:     sysUser.WLevel,
	}, nil
}

func UpdateSysUser(ctx context.Context, sysUser *model.My_user) error {
	err := db.GetDb().Transaction(func(tx *gorm.DB) error {
		err := tx.Updates(sysUser).Error
		if err != nil {
			log.Errorf("修改用户信息失败：%v", err)
			return err
		}

		err = tx.Where("user_id = ? and module = ?", sysUser.Id, consts.ModuleAdmin).Delete(&model.CoreUserHasRole{}).Error
		if err != nil {
			log.Errorf("修改用户信息失败：%v", err)
			return err
		}

		return nil
	})
	if err != nil {
		return sferrors.New(err).SetCode(sferrors.SystemError)
	}

	cacheKey := cache.GetUserCacheName(sysUser.Id, consts.ModuleAdmin)
	err = cache.RedisContextDelete(ctx, cacheKey)
	if err != nil {
		log.Errorf("删除用户角色缓存信息【%s】失败: %v", cacheKey, err)
	}
	return nil
}

func GetSysUserDetailById(uId uint64) (*model.SysUserDetail, error) {
	var userNew model.SysUserDetail
	err := db.GetDb().Where("id = ? and status = ?", uId, consts.StatusNormal).First(&userNew).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, nil
		}
		return nil, err
	}
	return &userNew, nil
}

func GetSysUserCountById(q string) (count int64) {
	var userNew model.SysUserDetail
	db.GetDb().Model(userNew).Where("q = ? and status = ?", q, consts.StatusNormal).Count(&count)
	return
}

func GetChildSysUserCountById(id uint64, isTure int) int64 {
	var count int64
	var userNew model.SysUserDetail
	if isTure == 0 {
		db.GetDb().Model(userNew).Where("pid = ? and status = ?", id, consts.StatusNormal).Count(&count)
	} else {
		db.GetDb().Model(userNew).Where("pid = ? and status = ? and is_task>0?", id, consts.StatusNormal).Count(&count)
	}
	return count
}

func GetWChildSysUserCountById(id uint64, isZhi int) int64 {
	var count int64
	var userNew model.SysUserDetail
	if isZhi == 0 {
		db.GetDb().Model(userNew).Where("w_pid = ? and status = ?", id, consts.StatusNormal).Count(&count)
	} else {
		db.GetDb().Model(userNew).Where("w_ppid = ? and status = ?", id, consts.StatusNormal).Count(&count)
	}
	return count
}

func GetWChildSysUserCountByIdss(id uint64, isZhi int) int64 {

	var userNew model.SysUserDetail
	myChildUser := []model.My_user{}
	if isZhi == 0 {
		db.GetDb().Model(userNew).Select("id").Where("pid = ? and status = ?", id, consts.StatusNormal).Find(&myChildUser)
	} else {
		db.GetDb().Model(userNew).Select("id").Where("ppid = ? and status = ?", id, consts.StatusNormal).Find(&myChildUser)
	}
	var count int64
	if len(myChildUser) > 0 {
		userIdMap := []uint64{}
		for _, user := range myChildUser {
			userIdMap = append(userIdMap, user.Id)
		}

		db.GetDb().Table("my_my_task").Where("tid=13 and days = ? and uid in(?)", time.Now().Format("20060102"), userIdMap).Count(&count)
	}

	return count
}

func GetChildNexSysUserCountById(id uint64, isTure int) int64 {
	var count int64
	var userNew model.SysUserDetail
	if isTure == 0 {
		db.GetDb().Model(userNew).Where("ppid = ? and status = ?", id, consts.StatusNormal).Count(&count)
	} else {
		db.GetDb().Model(userNew).Where("ppid = ? and status = ? and is_task>0", id, consts.StatusNormal).Count(&count)
	}
	return count
}
func Get30ChildNexSysUserCountById(id uint64, isType int) int64 {
	var count int64
	var userNew model.SysUserDetail
	if isType == 0 {
		db.GetDb().Model(userNew).Where("pid = ?  and level>=30", id).Count(&count)
	} else {
		db.GetDb().Model(userNew).Where("ppid = ? and level>=30", id).Count(&count)
	}
	return count
}

func GetAllSysUserDetailById(uId uint64) (*model.SysUserDetail, error) {
	var userNew model.SysUserDetail
	err := db.GetDb().Where("id = ? ", uId).First(&userNew).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, nil
		}
		return nil, err
	}
	return &userNew, nil
}

func DeleteSysUser(ctx context.Context, sysUser *model.SysUser) error {
	sysUser.Email = getDelEmail(sysUser.Email)
	err := db.GetDb().Model(model.SysUser{}).Where("id = ?", sysUser.Id).Update("email", sysUser.Email).Update("deleted_at", time.Now()).Error
	if err != nil {
		return err
	}
	cacheKey := cache.GetUserCacheName(sysUser.Id, consts.ModuleAdmin)
	err = cache.RedisContextDelete(ctx, cacheKey)
	if err != nil {
		log.Errorf("删除用户角色缓存信息【%s】失败: %v", cacheKey, err)
	}
	return nil
}

func ResetMyUserPayPassword(ctx context.Context, sysUser *model.SysUserDetail) error {
	return db.GetDb().Model(&model.My_user{}).Where("id = ?", sysUser.Id).Update("pwd", sysUser.Pwd).Error
}

func ResetSysUserPassword(ctx context.Context, sysUser *model.SysUserDetail) error {
	err := db.GetDb().Model(&model.My_user{}).Where("id = ?", sysUser.Id).Update("password", sysUser.PasswordHash).Error
	if err != nil {
		return err
	}
	cacheKey := cache.GetUserCacheName(sysUser.Id, consts.ModuleAdmin)
	err = cache.RedisContextDelete(ctx, cacheKey)
	if err != nil {
		log.Errorf("删除用户角色缓存信息【%s】失败: %v", cacheKey, err)
	}
	return nil
}

func getDelEmail(email string) string {
	if strings.Contains(email, "del-") {
		index := strings.LastIndex(email, "-")
		email = email[index+1:]
	}
	return fmt.Sprintf("del-%d-%s", time.Now().Unix(), email)
}

func IsAdvisorExistOfAgencyByUserId(userId uint64) (bool, error) {
	count := int64(0)
	if err := db.GetDb().Table("agencies").Where("advisor_id = ?", userId).Count(&count).Error; err != nil {
		return false, err
	}
	return count > 0, nil
}
func GetChildSysUserMax9CountById(id uint64) bool {
	ctx := context.TODO()
	key := fmt.Sprintf("uid:max_child:%d", id)
	con, err := cache.RedisContextGet[bool](ctx, key)
	if err == nil && con != nil && *con == true {
		//有9个就可以 不然不行
		return true
	}
	var count int64
	var userNew model.SysUserDetail
	db.GetDb().Model(userNew).Where("pid = ? and status = ? and is_task>0", id, consts.StatusNormal).Count(&count)
	if count > 8 {
		cache.RedisContextSet(ctx, key, true, 0)
		return true
	}
	return false
}
